package cn.support.neo.mvp.core.helper;

import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.kennyc.view.MultiStateView;
import com.orhanobut.logger.Logger;

import javax.inject.Inject;
import javax.inject.Singleton;

import cn.neo.support.recyclerview.material.MaterialRefreshLayout;
import cn.support.neo.mvp.R;
import cn.support.neo.mvp.core.base.Constants;
import cn.support.neo.mvp.core.base.ResultException;
import cn.support.neo.mvp.core.event.LogoutEvent;
import cn.support.neo.mvp.core.provider.AccountUtils;
import cn.support.neo.mvp.core.provider.EventBusProvider;
import cn.support.neo.mvp.model.qualifier.ResultCode;
import eu.unicate.retroauth.AuthAccountManager;

/**
 * Name:错误处理持有者
 * Author: WK（wangkun@xjzhicheng.com)
 * Date: 2016-08-12
 * Describe: PLEASE TO FIXME...
 */
@Singleton
public class ResultErrorHelper {


    @Inject
    ResultErrorHelper() {
    }

    @Inject
    AccountManager accountManager;
    @Inject
    AuthAccountManager authAccountManager;


    public void handler(final Context context, MultiStateView multiStateView, MaterialRefreshLayout refreshView, int pageIndex, Throwable throwable) {
        ResultException error;
        if (throwable instanceof ResultException) {//服务器返回错误
            error = (ResultException) throwable;
        } else {
            //其他错误
            error = ExceptionHandler.handleException(throwable);
        }
        switch (error.getErrCode()) {
            case ResultCode.REAL_VERIFY:
                Toast.makeText(context, "请先实名认证", Toast.LENGTH_SHORT).show();
                /*//跳转实名认证
                Intent intent = new Intent(context, MyAttestPage.class);
                context.startActivity(intent);
                //销毁当前页面
                context.finish();*/
                if (multiStateView != null) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    setShowText4Error(multiStateView, "请先实名认证(我的->设置->实名认证)");
                }
                break;
            case ResultCode.IDENTITY_VERIFICATION_FAILURE:
                //身份验证失败,重新登陆
                EventBusProvider.getInstance().post(new LogoutEvent(false, true));
                Toast.makeText(context, "身份验证失败", Toast.LENGTH_SHORT).show();
                if(context instanceof Activity){
                    Activity activity = (Activity) context;
                    AccountUtils.needLogin(activity, authAccountManager);
                    activity.finish();
                }
                break;
            case ResultCode.TOKEN_OVERDUE:
                //身份验证过期
                //使用变压器拦截
                Logger.i("Token Overdue(令牌过期)，没有走RetryTransFormer。。");
                if (multiStateView != null) {
                    if (refreshView != null) {
                        refreshView.finishRefresh();
                    }
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                }
                break;
            case ResultCode.DATA_NOT_EXIST:
                //没有更多数据延迟
                if (pageIndex == Constants.IGNORE) {
                    if (multiStateView != null) {
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                    }
                } else if (pageIndex == 1) {
                    if (multiStateView != null) {
                        if (refreshView != null) {
                            refreshView.finishRefresh();
                        }
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                    }
                } else if (pageIndex > 1) {
                    if (refreshView != null) {
                        refreshView.finishRefresh();
                        refreshView.finishRefreshLoadMore();
                        refreshView.setLoadMore(false);
                    }
                    if (multiStateView != null) {
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    }
                }
                Toast.makeText(context, "没有更多内容了", Toast.LENGTH_SHORT).show();
                break;
            case ResultCode.PARAM_VALIDATE_FAILED:
                if (multiStateView != null) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    setShowText4Error(multiStateView, "参数验证失败");
                }
                break;
            case ResultCode.OPERATE_FAILED:
                if (multiStateView != null) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    setShowText4Error(multiStateView, "操作失败");
                }
                break;
            case ResultCode.DATA_HAS_BEEN_DELETED:
                if (multiStateView != null) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    setShowText4Error(multiStateView, "该内容不存在或已被删除");
                }
                break;
            case ResultCode.SERVER_ERROR:
                if (multiStateView != null) {
                    multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                    setShowText4Error(multiStateView, "服务器错误");
                }
                break;
            // -------------------------------------------输入验证------------------------------
            /* case ResultCode.USER_ALREADY_EXISTS:
                Toast.makeText(context, "对不起，该用户已存在", Toast.LENGTH_SHORT).show();
                break;
            case ResultCode.PHONE_ALREADY_EXISTS:
                Toast.makeText(context, "对不起，该手机号已被使用", Toast.LENGTH_SHORT).show();
                break;
            case ResultCode.VERIFY_CODE_NOT_CORRECT:
                Toast.makeText(context, "验证码有误,请重新输入", Toast.LENGTH_SHORT).show();*/
            // -------------------------------------------网络连接错误------------------------------
            case ResultCode.HTTP:
            case ResultCode.UNKNOWN:
            case ResultCode.CONVERSION:
            case ResultCode.SSL_ERROR:
            case ResultCode.NETWORK:
                if (pageIndex == Constants.IGNORE) {
                    if (multiStateView != null) {
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        setShowText4Error(multiStateView, error.getMessage());
                    } else {
                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else if (pageIndex == 1) {//加载第一页没有数据
                    if (multiStateView != null) {
                        if (refreshView != null) {
                            refreshView.finishRefresh();
                        }
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        setShowText4Error(multiStateView, error.getMessage());
                    }
                } else if (pageIndex > 1) {
                    if (refreshView != null) {
                        refreshView.finishRefresh();
                        refreshView.finishRefreshLoadMore();
                    }
                    if (multiStateView != null) {
                        multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    }
                    Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
                }

                break;
            default:
                Toast.makeText(context, "未知错误：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                break;
        }
    }


    /**
     * 设置空，显示的text
     *
     * @param mMultiStateView mMultiStateView
     * @param message         显示的文本
     */
    private void setShowText4Empty(MultiStateView mMultiStateView, String message) {
        View view = mMultiStateView.getView(MultiStateView.VIEW_STATE_EMPTY);
        TextView tvEmpty = (TextView) view;
        tvEmpty.setText(message);

    }

    /**
     * 设置错误显示的text
     *
     * @param mMultiStateView mMultiStateView
     * @param message         显示的文本
     */
    private void setShowText4Error(MultiStateView mMultiStateView, String message) {
        View view = mMultiStateView.getView(MultiStateView.VIEW_STATE_ERROR);
        TextView tvErr = (TextView) view.findViewById(R.id.tv_err);
        tvErr.setText(message);
    }
}
